#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <strings.h>
#include <cstdlib>
#include <netinet/in.h>
#include <arpa/inet.h>





namespace ns_server
{
    enum{
        SOCKET_ERR = 1,
        BIND_ERR = 2
    };
    class UdpServer
    {
        const static uint16_t default_port = 8080;
    public:
        UdpServer(std::string ip,uint16_t port = default_port)
        : _ip(ip)
        , _port(port)
        {
            std::cout << "server addr: " << _ip << " : " << _port << std::endl;
        }


        void InitServer()
        {
            //1.创建套接字，指定基于网络通信和udp数据报协议
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);
            if(_sockfd < 0)
            {
                std::cerr << "creat socket erro:" << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cerr << "creat socket success:" << _sockfd << std::endl;

            //2.绑定端口号
            struct sockaddr_in local;
            bzero(&local,sizeof(local));  //所有bit设置为0

            local.sin_family = AF_INET;     //指明服务类型为网络通信
            local.sin_port = htons(_port);  //指明端口号，因为端口号要发送至客户端，调整为大端序列
            local.sin_addr.s_addr = inet_addr(_ip.c_str()); //指明ip，转换为4字节int类型，调整为大端序列

            int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
            if(n < 0)
            {
                std::cerr << "bind socket erro:" << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << _sockfd << std::endl;

        }
        void Start()
        {

        }
        ~UdpServer()
        {

        }

    private:
        int _sockfd;
        std::string _ip;
        uint16_t _port;  //端口号：俩个字节

    };
}